/**
 * 
 */
package com.nishop.api.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;

/**
 * @author liuwenlai
 *
 */
public class FileUtil {

	/**
	 * 写入文件
	 * 
	 * @param file
	 * @param inputStream
	 */
	public static void writeFile(File file, InputStream inputStream) {
		FileOutputStream os = null;
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[1024];
			while ((bytesRead = inputStream.read(buffer)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
		} catch (Exception e) {
			throw new RuntimeException("调用inputStreamToFile产生异常：", e);
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				throw new RuntimeException("inputStreamToFile关闭io产生异常：", e);
			}
		}
	}

	public static void readFile(String filePath, OutputStream outputStream) {
		InputStream in = null;
		try {
			in = new FileInputStream(filePath);
			int len = 0;
			byte[] buffer = new byte[1024];
			while ((len = in.read(buffer)) > 0) {
				outputStream.write(buffer, 0, len);
			}

		} catch (Exception e) {

			if (in != null) {
				try {
					in.close();
				} catch (IOException e1) {
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e1) {
				}
			}
		}
	}

	public static String getFileFullPath(String folderPath) {
		String filePath = "";
		Collection<File> files = FileUtils.listFiles(new File(folderPath),
				FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE),
				FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE));

		if (files.size() > 0) {
			File file = (File) files.toArray()[0];
			filePath = folderPath + File.separator + file.getName();
		}
		return filePath;
	}

}
